from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models import Homework
from schemas import HomeworkCreate, HomeworkOut
from typing import List
import json

router = APIRouter()

# 增：老师布置作业
@router.post("/", response_model=HomeworkOut)
def create_homework(homework: HomeworkCreate, db: Session = Depends(get_db)):
    db_homework = Homework(
        title=homework.title,
        description=homework.description,
        problems=json.dumps(homework.problems),  # 列表转JSON字符串
        deadline=homework.deadline,
        teacher_id=homework.teacher_id
    )
    db.add(db_homework)
    db.commit()
    db.refresh(db_homework)

    # 转换回来 problems
    return HomeworkOut(
        id=db_homework.id,
        title=db_homework.title,
        description=db_homework.description,
        problems=json.loads(db_homework.problems),
        deadline=db_homework.deadline,
        teacher_id=db_homework.teacher_id
    )

# 查：获取所有作业
@router.get("/", response_model=List[HomeworkOut])
def get_homeworks(db: Session = Depends(get_db)):
    homeworks = db.query(Homework).all()
    result = []
    for hw in homeworks:
        result.append(HomeworkOut(
            id=hw.id,
            title=hw.title,
            description=hw.description,
            problems=json.loads(hw.problems),
            deadline=hw.deadline,
            teacher_id=hw.teacher_id
        ))
    return result

# 查：获取某个作业
@router.get("/{homework_id}", response_model=HomeworkOut)
def get_homework(homework_id: int, db: Session = Depends(get_db)):
    hw = db.query(Homework).filter(Homework.id == homework_id).first()
    if not hw:
        raise HTTPException(status_code=404, detail="作业不存在")
    return HomeworkOut(
        id=hw.id,
        title=hw.title,
        description=hw.description,
        problems=json.loads(hw.problems),
        deadline=hw.deadline,
        teacher_id=hw.teacher_id
    )

